/*
* 包含n个reducer函数，根据老的state和指定的action返回一个新的state
* */
import {combineReducers} from 'redux'

import {getRedirectTo} from "../utils";
import {AUTH_Success,ERROR_MSG,RESET_USER,RECEIVE_USER,RECEIVE_USERLIST,RECEIVEANMSG,RECEIVE_CHATMSGLIST,MSGREAD} from "./action-types";

const initUser ={
    username:'',//后台返回的用户名
    type:'',//后台返回的用户类型
    msg:'',//后台返回的错误提示信息
    redirectTo :''
}
//管理用户信息的reducer
function user(state =initUser,action) {

    switch (action.type) {
        case AUTH_Success://这种情况下data是user
            const {type,header} = action.data
            console.log(type)
            return {...action.data,redirectTo: getRedirectTo(type,header)}
        case ERROR_MSG://这种情况data是msg
            return {...state,msg: action.data}
        case RECEIVE_USER://接收到用户
            return action.data
        case RESET_USER://重置用户
            return {...initUser,msg:action.data}
        default :
            return state
    }

}

const initUserList =[]
//管理用户列表的reducer
function userlist(state = initUserList,action) {
    switch (action.type) {
        case RECEIVE_USERLIST:
            return action.data
        default:
            return state
    }

}
const initchatmsg = {
    users : {},
    chatMsgs :[],
    unReadcount:0
}
//管理聊条记录的reducer
function chatmsg(state = initchatmsg,action) {
    switch (action.type) {
        case RECEIVE_CHATMSGLIST:
            const {users,chatMsgs,current_userid} = action.data
            //测试
            //console.log("消息列表",action)
            return {
                users,
                chatMsgs,
                unReadcount: chatMsgs.reduce((pre,msg)=>{
                    return pre+((msg.to===current_userid&&!msg.read)? 1:0)
                },0)
            }
        case RECEIVEANMSG:
            const {chat_msg} = action.data
            //测试
          //  console.log("这是收到消息之后的userid",userid)
            return {
                users : state.users,
                chatMsgs :[...state.chatMsgs,chat_msg],
                unReadcount:state.unReadcount + ((chat_msg.to===action.data.current_userid&&!chat_msg.read)? 1:0)
            }
            //更新已读消息read为true,但是reducer是纯函数，不能修改原来的state,
        case MSGREAD:
            const {from,to,readcount} = action.data
            return {
                users : state.users,
                chatMsgs :state.chatMsgs.map(msg=>{
                    if (msg.to === to&&msg.from ===from&&!msg.read){
                        //注意，这里不能写 msg.read =true,return msg,因为修改了state，不满足纯函数的条件
                        return{...msg,read:true}
                    }
                    else{
                        return msg
                    }
                }),
                unReadcount:state.unReadcount -readcount
            }
        default:
            return state
    }
}
export default combineReducers({
    user,
    userlist,
    chatmsg
})
//向外暴露的状态结构：{user:{}}

